/*
 * Copyright 1999-2101 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.fastjson.serializer.ext;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import com.alibaba.fastjson.serializer.FieldSerializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.FieldInfo;

/**
 * 枚舉序列化實現
 * @author kenti
 */
final class EnumFieldSerializer extends FieldSerializer {

    public EnumFieldSerializer(FieldInfo fieldInfo){
        super(fieldInfo);
    }

    public void writeProperty(JSONSerializer serializer, Object propertyValue) throws Exception {
        writePrefix(serializer);
        this.writeValue(serializer, propertyValue);
    }
    
    public String writeStr(JSONSerializer serializer, String str){
    	if (serializer.isEnabled(SerializerFeature.QuoteFieldNames)) {
            if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
            	return '\'' + str + "\'";
            } else {
            	return '"' + str + "\""; 
            }
        } else {
        	return str;
        }
    }
    
    public String writeStr2(JSONSerializer serializer, Object str){
    	if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
    		return '\'' + (str + "\'");
        } else {
        	 return '"' + (str + "\"");
        }
    }
    
    @Override
    public void writeValue(JSONSerializer serializer, Object propertyValue) throws Exception {
        SerializeWriter out = serializer.getWriter();
        Field[] fields =propertyValue.getClass().getDeclaredFields();
        StringBuffer sb=new StringBuffer("{");
		for (Field field : fields) {
			if(!Modifier.isStatic(field.getModifiers())){
				field.setAccessible(true);
				String fieldName=field.getName();
				String fieldNameB=field.getName().substring(0, 1);
				String methodName="get"+ fieldName.replace(fieldNameB, fieldNameB.toUpperCase());
				Method method=propertyValue.getClass().getMethod(methodName);
				Object res=method.invoke(propertyValue);
				sb.append(writeStr(serializer, fieldName)+":");
				sb.append(writeStr2(serializer, res)+",");
				field.setAccessible(false);
			}
		}
		out.write(sb.substring(0, sb.length()-1));
		out.write("}");
    }
}
